package com.example.dw.service.impl;

import com.example.dw.entity.User;
import com.example.dw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 自定义用户详情服务
 * @author system
 * @since 2024-01-01
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 根据角色设置权限
        String roleName = getRoleName(user.getRole());
        List<SimpleGrantedAuthority> authorities = Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_" + roleName)
        );

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .accountExpired(false)
                .accountLocked(user.getStatus() != 0)
                .credentialsExpired(false)
                .disabled(user.getDeleteStatus() != 0)
                .build();
    }

    private String getRoleName(Integer role) {
        if (role == null) {
            return "STUDENT";
        }
        switch (role) {
            case 0:
                return "STUDENT";
            case 1:
                return "TEACHER";
            case 2:
                return "ADMIN";
            default:
                return "STUDENT";
        }
    }
} 